package com.example.crawler.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

public class HttpClientUtil {
    private static CloseableHttpClient httpclient = null;

    public static String getBaseEntInfo(String url, String entName) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = null;
        if (StringUtils.isEmpty(entName)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?entName=" + entName);
        }
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                return s;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return null;
    }

    public static JSONObject sendPost(String url, String jsonString) {
        JSONObject jsonObject = new JSONObject();
        String body = "";
        try {
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);

            //装填参数
            StringEntity s = new StringEntity(jsonString, "utf-8");
            s.setContentEncoding(new BasicHeader("contentType",
                    "application/json"));
            //设置参数到请求对象中
            httpPost.setEntity(s);
            //System.out.println("请求地址：" + url);

            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            //httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSON.parseObject(body);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static JSONObject doGet(String url, Map<String, String> param) {
        JSONObject jsonObject = new JSONObject();
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                jsonObject = JSONObject.parseObject(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    //调用图库服务
    public static String getGroupEntInfo(String url, String cid, String type) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = null;
        StringBuilder sb = new StringBuilder(url);
        //配置超时
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
//                .setSocketTimeout(1000000).build();
        if (StringUtils.isEmpty(cid)) {
            httpGet = new HttpGet(url);
        } else {
            sb.append("?cid=").append(cid);
            if (StringUtils.isNotEmpty(type)) {
                sb.append("&type=").append(type);
            }
            httpGet = new HttpGet(sb.toString());
        }
//        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                return s;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return null;
    }


    /*public static void main(String[] args) {
        String json = null;
        try {
            json = getBaseEntInfo("http://172.30.7.126:9071/getNegativeByEnt","科大讯飞股份有限公司");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,Object> parse =(Map) JSONObject.parse(json);
        System.out.println(parse.get("total"));
    }*/
}
